package com.linktco.common.aop;


import com.linktco.common.utils.U;
import com.linktco.common.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Mapper AOP
 *
 * @author zhangnx
 */
@Aspect
@Component
@Slf4j
public class MapperAop {


    @Before("execution(* com.linktco.*.mapper.*.insert(..))")
    public void insertBefore(JoinPoint point) {
        Object[] args = point.getArgs();
        Object obj = args[0];
        try {
            for (Field field : getAllFields(obj)) {
                if (field.getName().equals("createDept")) {
                    Long organId = UserUtil.getOrganId();
                    setField(field, obj, organId);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Field[] getAllFields(Object object){
        Class clazz = object.getClass();
        List<Field> fieldList = new ArrayList<>();
        while (clazz != null){
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        return fields;
    }

    private void setField(Field field, Object obj, Object value) throws IllegalAccessException {
        if (U.isEmpty(field, obj)) {
            return;
        }

        field.setAccessible(true);
        Object organIdValue = field.get(obj);
        if (U.isEmpty(organIdValue)) {
            field.set(obj, value);
        }else {
            field.set(obj, organIdValue);
        }
        field.setAccessible(false);
    }



}



